<template>
  <view class="address-box">
    <!-- 选择收货地址 -->
    <view class="select-address" v-if="JSON.stringify(address) === '{}'"><button type="primary" size="mini" @click="chooseAddressPageShow">选择收货地址+</button></view>
    <!-- 收货地址信息 -->
    <view class="address-info" v-else @click="chooseAddressPageShow">
      <view class="info-top">
        <text>收货人:&nbsp;&nbsp;{{ address.userName }}</text>
        <view class="phone-number">
          <text>电话:&nbsp;&nbsp;{{ address.telNumber }}</text>
          <uni-icons type="arrowright" size="16"></uni-icons>
        </view>
      </view>
      <view class="info-bottom">
        <text>收货地址:</text>
        <view>{{ addressStr }}</view>
      </view>
    </view>
    <!-- 分割线 -->
    <image src="../../static/cart_border@2x.png"></image>
  </view>
</template>

<script>
import { mapState, mapGetters, mapMutations } from 'vuex';
export default {
  data() {
    return {
      // address:{},//收货地址信息
    };
  },
  computed: {
    ...mapState('myAddress', ['address']),
    ...mapGetters('myAddress', ['addressStr'])
  },
  methods: {
    ...mapMutations('myAddress', ['updataAddress']),
    async chooseAddressPageShow() {
      const [error, success] = await uni.chooseAddress().catch(err => err);
      // 用户没有授权
      if (error && (error.errMsg === 'chooseAddress:fail auth deny' || err.errMsg === 'chooseAddress:fail authorize no response')) {
        this.reAuth(); // 调用 this.reAuth() 方法，向用户重新发起授权申请
      }
      // 用户有授权
      if (error === null && success.errMsg === 'chooseAddress:ok') {
        this.updataAddress(success);
      }
    },
    reAuth() {
      const res = uni.showModal({
        title: '提示',
        content: '检测到您还没有授权获取收货地址,是否重新获取权限',
        success: function(res) {
          if (res.confirm) {
            console.log('用户点击确定');
            uni.openSetting({
              success: settingResult => {
                // 3.4.2 地址授权的值等于 true，提示用户 “授权成功”
                if (settingResult.authSetting['scope.address']) return uni.$showMsg('授权成功！请选择地址');
                // 3.4.3 地址授权的值等于 false，提示用户 “您取消了地址授权”
                if (!settingResult.authSetting['scope.address']) return uni.$showMsg('您取消了地址授权！');
              }
            });
          } else if (res.cancel) {
            uni.$showMsg('您取消了授权');
          }
        }
      });
    }
  },
  mounted() {
    console.log(this.address);
  }
};
</script>

<style lang="scss">
.address-box {
  image {
    display: block;
    width: 100%;
    height: 5px;
  }
  .select-address {
    height: 160rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .address-info {
    padding: 15rpx 15rpx 20rpx;

    font-size: 28rpx;
    .info-top {
      display: flex;
      justify-content: space-between;
      margin-bottom: 15rpx;
    }
    .info-bottom {
      display: flex;
      view {
        flex: 1;
        padding-left: 15rpx;
      }
    }
  }
}
</style>
